package com.jmhy.sdk.activity.View;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewTreeObserver;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.jmhy.sdk.activity.BaseFloatActivity;
import com.jmhy.sdk.config.AppConfig;
import com.jmhy.sdk.utils.AndroidBug5497Workaround;
import com.jmhy.sdk.utils.FloatJsInterface;
import com.jmhy.sdk.utils.FloatUtils;
import com.jmhy.sdk.utils.Logger;

public class UserLoginNoticeView extends BaseFloatActivity {
    private static final String TAG = "FloatUserInfoView";
    private WebView mWebview;


    private String mUrl;
    private View back_view;

    private int mWbeHeight;


    private boolean isShowKeyboard;
    private int reduceHeight;
    private CloseFloatListener closeFloatListener;


    public UserLoginNoticeView(Activity activity, CloseFloatListener listener) {
        super(activity);
        Logger.d("UserLoginNoticeView");
        this.closeFloatListener = listener;
    }


    @Override
    public void setContentView(@NonNull int layout_id) {
        super.setContentView(layout_id);
    }


    @Override
    public void setViews(String url) {
        if (contentView != null) {
            return;
        }

//        mUrl = "https://apisdk.5tc5.com/sdk_new/dist/#/bag?_t=1603280634347";
        mUrl = url;
        intView();

        //防止软键盘覆盖webview
        mWebview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                if (mWebview != null) {
                    mWbeHeight = mWebview.getHeight();
                    Rect r = new Rect();
                    //获取当前界面可视部分
                    activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                    //获取屏幕的高度
                    int screenHeight = activity.getWindow().getDecorView().getRootView().getHeight();
                    //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                    int heightDifference = screenHeight - r.bottom;

                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mWebview.getLayoutParams();
                    if (heightDifference > 150 && !isShowKeyboard) {
                        reduceHeight = mWbeHeight - (mWbeHeight - heightDifference);
                        layoutParams.height = mWbeHeight - heightDifference;
                        mWebview.setLayoutParams(layoutParams);
                        isShowKeyboard = true;
                    } else if (heightDifference < 150 && isShowKeyboard) {
                        isShowKeyboard = false;
                        layoutParams.height = mWbeHeight + reduceHeight;
                        mWebview.setLayoutParams(layoutParams);
                    }
                }
            }
        });
    }

    @Override
    public void removeContentView() {
        super.removeContentView();

        if (contentView != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    ViewParent parent = contentView.getParent();
                    ViewGroup viewGroup = (ViewGroup) parent;
                    ViewGroup viewGroup1 = (ViewGroup) contentView;

                    viewGroup1.removeAllViews();

                    viewGroup.removeView(contentView);


                    contentView = null;
                    closeFloatListener.closeFloat();
                }
            });

        }
    }

    @Override
    public void show() {
        super.show();
    }

    @Override
    public boolean isShow() {
        return super.isShow();
    }

    private void intView() {

        int layout_id = 0;

        layout_id = AppConfig.resourceId(activity, "jmnotice", "layout");

        setContentView(layout_id);
        AndroidBug5497Workaround.assistActivity(activity);
        back_view = contentView.findViewById((AppConfig.resourceId(activity, "back_view", "id")));
        if (back_view != null) {
            back_view.setOnClickListener(this);
        }
        mWebview = contentView.findViewById(AppConfig.resourceId(activity, "webview", "id"));
        mWebview.setBackgroundColor(0);
        mWebview.getBackground().setAlpha(0);


//        mWebview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        mWebview.setVerticalScrollBarEnabled(false);
        mWebview.getSettings().setSupportZoom(false);
        mWebview.getSettings().setSaveFormData(false);
        mWebview.getSettings().setSavePassword(false);
        mWebview.getSettings().setJavaScriptEnabled(true);
        mWebview.getSettings().setBuiltInZoomControls(false);
        mWebview.getSettings().setSupportZoom(false);
        mWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);// 默认不使用缓存！

        mWebview.getSettings().setDomStorageEnabled(true);


        mWebview.addJavascriptInterface(new FloatJsInterface(activity, this), "jimiJS");
        mWebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        // 修复一些机型webview无法点击****/
        mWebview.requestFocus(View.FOCUS_DOWN);
        mWebview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Log.i(TAG, "onPageStarted " + url);
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i(TAG, "onPageFinished " + url);
                super.onPageFinished(view, url);

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i(TAG, "shouldOverrideUrlLoading " + url);
                String lowcaseUrl = url.toLowerCase();
                if (lowcaseUrl.startsWith("weixin://wap/pay")) {
                    Intent intent = null;

                    try {
                        intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                        view.getContext().startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                } else if (lowcaseUrl.startsWith("alipays://platformapi/startapp")) {
                    try {
                        Log.i("JiMiSDK", "uuuuuuuuuuuuu");

                        Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                        view.getContext().startActivity(intent);


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                } else {
                    return super.shouldOverrideUrlLoading(view, url);
                }
            }

        });
        mWebview.setWebChromeClient(new WebChromeClient());
        mWebview.loadUrl(mUrl);
    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v.getId() == AppConfig.resourceId(activity, "iphoneback", "id")) {
            if (mWebview.canGoBack()) {
                mWebview.goBack();
            } else {
                // TODO Auto-generated method stub
            }
        } else if (v.getId() == AppConfig.resourceId(activity, "iv_right_colse", "id")) {
            removeContentView();
            closeFloatListener.closeFloat();
        } else if (v.getId() == AppConfig.resourceId(activity, "iv_left_colse", "id")) {
            removeContentView();
            closeFloatListener.closeFloat();
        } else if (v.getId() == AppConfig.resourceId(activity, "content", "id")) {

        } else if (v.getId() == AppConfig.resourceId(activity, "back_view", "id")) {

        }
    }


    public interface CloseFloatListener {

        void closeFloat();

    }


    @Override
    public void closeWebPageAndOpenTurntable(final String url) {
        super.closeWebPageAndOpenTurntable(url);
        removeContentView();

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                FloatUserOpenTurntableView floatUserOpenTurntanleActivity = new FloatUserOpenTurntableView(activity, new FloatUserOpenTurntableView.CloseFloatListener() {
                    @Override
                    public void closeFloat() {
                        FloatUtils.showFloat(activity);
                    }
                });

                floatUserOpenTurntanleActivity.setViews(url);
                floatUserOpenTurntanleActivity.show();
            }
        });

    }

    @Override
    public void closeWebPageAndOpenUserCenter(final String url) {
        super.closeWebPageAndOpenUserCenter(url);
        removeContentView();
        FloatUtils.destroyFloat();
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                FloatUserInfoView floatUserInfoView = new FloatUserInfoView(activity, new FloatUserInfoView.CloseFloatListener() {
                    @Override
                    public void closeFloat() {
                        FloatUtils.showFloat(activity);
                    }
                });

                floatUserInfoView.setViews(url);
                floatUserInfoView.show();
            }
        });

    }

    @Override
    public void closeWebView() {
        super.closeWebView();
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                FloatUtils.showFloat(activity);
            }
        });
    }
}
